package net.wanho.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.druid.sql.visitor.functions.If;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import net.wanho.constant.UserConstant;
import net.wanho.dto.*;
import net.wanho.mapper.RoleMapper;
import net.wanho.mapper.UserRoleMapper;
import net.wanho.po.UserInfo;
import net.wanho.po.UserRole;
import net.wanho.service.FileService;
import net.wanho.service.UserInfoService;
import net.wanho.mapper.UserInfoMapper;
import net.wanho.util.ThreadUtil;
import net.wanho.vo.*;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author Administrator
* @description 针对表【user_info(用户表)】的数据库操作Service实现
* @createDate 2025-04-28 11:41:58
*/
@Service
@RequiredArgsConstructor
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo>
    implements UserInfoService{

    private final UserInfoMapper userInfoMapper;

    private final StringRedisTemplate redisTemplate;

    private final RoleMapper roleMapper;

    private final FileService fileService;
    private final UserRoleMapper userRoleMapper;


    @Override
    public UserInfo findByName(String userCode) {
        return userInfoMapper.selectByName(userCode);
    }

    @Override
    public UserVo find() {
        // 后台通过token获取用户id，然后返回当前登录用户的信息
        Integer id = ThreadUtil.getId();

        UserInfo userInfo = userInfoMapper.selectById(id);
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(userInfo, userVo);
        return userVo;
    }

    @Override
    public PageInfo<UserInfo> listPage(Integer pageNum, Integer pageSize, UserInfoDTO userInfoDTO) {

        Page<UserInfo> page = new Page<>(pageNum, pageSize);

        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.like(!ObjectUtil.isEmpty(userInfoDTO.getUserCode()), "u.user_code", userInfoDTO.getUserCode());
        wrapper.eq(!ObjectUtil.isEmpty(userInfoDTO.getRoleId()), "r.role_id", userInfoDTO.getRoleId());
        wrapper.eq(!ObjectUtil.isEmpty(userInfoDTO.getUserState()), "u.user_state", userInfoDTO.getUserState());


        Page<UserInfo> p = this.baseMapper.selectByPage(page, wrapper);

        PageInfo<UserInfo> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page.getCurrent());
        pageInfo.setPageSize(page.getSize());
        pageInfo.setTotalNum(page.getTotal());
        pageInfo.setPageCount(page.getPages());
        pageInfo.setLimitIndex(page.offset());
        pageInfo.setResultList(p.getRecords());
        return pageInfo;
    }

    @Override
    public void addUser(AddDTO addDTO) {
        if(!addDTO.getUserPwd().equals(addDTO.getConfirmPassword())){
            throw new RuntimeException("密码不一致,请重新输入");
        }
        if(userInfoMapper.selectByName(addDTO.getUserCode()) != null){
            throw new RuntimeException("用户名已存在,请重新输入");
        }

        UserInfo userInfo = new UserInfo();
        userInfo.setUserPwd(SecureUtil.md5(addDTO.getUserPwd()));
        userInfo.setUserCode(addDTO.getUserCode());
        userInfo.setUserName(addDTO.getUserName());
        Integer id = ThreadUtil.getId();
        userInfo.setCreateBy(id);
        userInfo.setUpdateBy(id);
        userInfo.setUserState(UserConstant.USER_ENABLE);
        userInfo.setIsDelete(UserConstant.NOT_DELETED);
        LocalDateTime  now = LocalDateTime.now();
        userInfo.setCreateTime(now);
        userInfo.setUpdateTime(now);

        userInfoMapper.putUser(userInfo);
        // 给用户添加默认角色
        UserRole userRole = new UserRole();
        userRole.setUserId(userInfoMapper.selectByName(addDTO.getUserCode()).getUserId());
        userRole.setRoleId(1);
        userRoleMapper.insert(userRole);


    }

    @Override
    public void updateState(UserInfo userInfo) {
        // 获取当前用户状态
        UserInfo currentUser = userInfoMapper.selectById(userInfo.getUserId());

        // 根据当前状态设置新状态
        if (UserConstant.USER_ENABLE.equals(currentUser.getUserState())) {
            userInfo.setUserState(UserConstant.USER_DISABLE);
        } else {
            userInfo.setUserState(UserConstant.USER_ENABLE);
        }

        // 设置更新人和更新时间
        Integer updateBy = ThreadUtil.getId();
        userInfo.setUpdateBy(updateBy);
        userInfo.setUpdateTime(LocalDateTime.now());

        // 更新用户状态
        userInfoMapper.updateById(userInfo);
    }

    @Override
    public void updateName(UserDTO userDTO) {
        //UserInfo userInfo = userInfoMapper.selectById(userDTO.getUserId());
        userInfoMapper.updateName(userDTO);
    }

    @Override
    public void updatePwd(PwdDTO pwdDTO) {
        Integer id = ThreadUtil.getId();
        UserInfo userInfo = userInfoMapper.selectById(id);
        if (userInfo == null) {
            throw new RuntimeException("用户不存在");
        }
        if(!SecureUtil.md5(pwdDTO.getOldPassword()).equals(userInfo.getUserPwd())){
            throw new RuntimeException("旧密码错误");
        }
        if(!pwdDTO.getPassword().equals(pwdDTO.getRepeatPassword())){
            throw new RuntimeException("两次密码不一致");
        }
        userInfo.setUserPwd(SecureUtil.md5(pwdDTO.getPassword()));
        LocalDateTime now = LocalDateTime.now();
        userInfo.setUpdateTime(now);
        userInfoMapper.updateById(userInfo);
    }

    @Override
    public void updateMsg(MsgDTO msgDTO) {
        UserInfo userInfo = userInfoMapper.selectById(msgDTO.getUserId());

        userInfo.setUserCode(msgDTO.getUserCode());
        userInfo.setMobile(msgDTO.getMobile());
        userInfo.setEmail(msgDTO.getEmail());

        LocalDateTime now = LocalDateTime.now();
        userInfo.setUpdateTime(now);
        userInfoMapper.updateById(userInfo);
    }

    @SneakyThrows
    @Override
    public String ModifyAvatar(Integer id, MultipartFile file) {
        String url = fileService.upload(file.getOriginalFilename(), file.getInputStream());
        UserInfo userInfo = userInfoMapper.selectById(id);
        userInfo.setAvatar(url);
        userInfoMapper.updateById(userInfo);
        return url;
    }


}




